<template>
	<view class="container" :style="{height:`calc(100vh - ${height}px)`}">
		<Header back title="上传"></Header>
		<view class="wapper">
			<div class="content">
				<u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" name="1" multiple
					:maxCount="10"></u-upload>
			</div>
			<div class="footer">
				<u-button type='primary' text="上传" @click="submit" :loading="loading"></u-button>
			</div>
		</view>
	</view>
</template>

<script>
	import Header from '@/components/haeder.vue'
	import banner1 from '@/static/banner/banner1.png'
	export default {
		components: {
			Header
		},
		data() {
			return {
				height: 0,
				user: null,
				fileList: [],
				loading: false
			}
		},
		methods: {
			deletePic(event) {
				this.fileList.splice(event.index, 1)
			},
			async submit() {
				this.loading = true
				let PictureList = (this.fileList.map((v) => {
					let index = v.name.lastIndexOf('.')
					let name = v.name.slice(0, index)
					return {
						PictureName: name,
						FileName: v.name
					}
				}))
				let params = {
					OpenId: this.user.OpenID,
					ChangShangId: this.user.ZhanShangInfo.ZhangShangID,
					PictureList
				}
				let files = this.fileList.map((v)=>{
					return {
						name:v.name,
						file:v,
						uri:v.url
					}
				})
				await this.uploadFilePromise(params, files)

			},
			// 新增图片
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this.fileList.length
				lists.map((item) => {
					this.fileList.push({
						...item,
					})
				})
			},
			uploadFilePromise(params, files) {
				let that = this
				uni.uploadFile({
					url: that.baseUrl + '/API/User/PostUploadPictures', // 仅为示例，非真实的接口地址
					files,
					name: 'file',
					formData: {
						PicturesJson: JSON.stringify(params)
					},
					success: ({data}) => {
						that.loading = false
						let res = JSON.parse(data)
						if (res.Status == 0) {
							uni.$u.toast('上传成功!')
							setTimeout(() => {
								uni.redirectTo({
									url: '/pages/index/photo'
								})
							}, 1000)
						}
					}
				})
			}
		},
		onLoad(e) {

		},
		mounted() {
			this.user = uni.getStorageSync('user')
		},
		created() {
			let app = uni.getSystemInfoSync();
			this.height = app.windowBottom
		}
	}
</script>

<style scoped lang="scss">
	.container {
		width: 100vw;
		overflow: auto;
		display: flex;
		flex-direction: column;

		.wapper {
			flex: 1;
			background: #f2f2f2;
			z-index: 100;
			margin-top: -280rpx;
			border-top-left-radius: 60rpx;
			border-top-right-radius: 60rpx;
			padding: 40rpx;
			display: flex;
			flex-direction: column;
			justify-content: space-between;
		}
	}
</style>